/**
 * Copyright (c) 2010 Abadi Kurniawan, Brian Dukes
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package hackathon.android.mymessageinbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/**
 * @author Abadi Kurniawan, Brian Dukes
 *
 */
public abstract class MyService extends Service {
	public static final String INTENT_MESSAGE_UPDATE = "com.engage.mobile.MessageUpdate";
	public static final String INTENT_AUTHENTICATION = "com.engage.mobile.Authentication";
	
	public static final String EXTRA_MESSAGES = "messages";
	public static final String EXTRA_AUTHENTICATION = "authentication"; 
	public static final String EXTRA_TOKEN = "token";
	public static final String EXTRA_USERNAME = "userName";
	public static final String EXTRA_PAGE_INDEX = "pageIndex";
	public static final String EXTRA_PAGE_SIZE = "pageSize";
	public static final String EXTRA_WEB_SERVICE_URL = "webServiceUrl";
	
	private final String servicePath = "DesktopModules/MyMessagesInbox/Inbox.svc/";
	
	protected NotificationManager notificationManager;
	
	protected static int UPDATE_INTERVAL = 60000;
	protected static String SERVICE_URL = "";
	
	protected String token;
	protected String userName;
	
    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
	protected final IBinder mBinder = new MessageBinder();

	 /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class MessageBinder extends Binder {
    	MyService getService() {
            return MyService.this;
        }
    }
    
	@Override
	public void onCreate()
	{
		notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		Log.d("Engage","[Service created] "+ this.toString());
	}
	
	@Override
	public void onDestroy()
	{
		this.stopSelf();
		notificationManager.cancel(R.string.service_id);
		Log.d("Engage","[Service destroyed] "+ this.toString());
	}
	

	@Override
	public void onStart(Intent intent, int startId) {
		SERVICE_URL = intent.getExtras().getString(EXTRA_WEB_SERVICE_URL);
		
		if (!SERVICE_URL.endsWith("/")) {
			SERVICE_URL += "/";
		}
		SERVICE_URL += servicePath;		
	}
	
	protected static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
            	Log.d("Engage", "[buffer] "+line);
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
	
	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

    /**
     * Show a notification while this service is running.
     */
	protected void showNotification() {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        
        this.showNotification(text);
    }
	
	protected void showNotification(CharSequence text)
	{
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text, 
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        		new Intent(this, MyMessage.class)
        			.putExtra(MyService.EXTRA_TOKEN, token)
        			.putExtra(MyService.EXTRA_USERNAME, userName)
        		, 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label),
                       text, contentIntent);
        
        notification.defaults |= Notification.DEFAULT_SOUND;

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        notificationManager.notify(R.string.service_id, notification);
	}
}
